package com.server;

import java.util.Vector;

import com.client.Service;
import com.google.api.services.tasks.v1.model.Task;
import com.google.api.services.tasks.v1.model.TaskList;
import com.google.api.services.tasks.v1.model.TaskLists;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

import com.google.api.services.tasks.v1.Tasks;
import com.shared.TaskGrid;
import com.shared.Token;

/*
 * https://appengine.google.com/
 * https://code.google.com/apis/console
 * http://alainrussier.appspot.com/
 * http://code.google.com/p/googletasksearch/
 * 
 */

/**
 * The server side implementation of the RPC service.
 * TODO ajouter l'arborescence des taches
 * TODO envoyer sur les log sur les log app engine
 */
public class ServiceImpl extends RemoteServiceServlet implements Service {    
 // The clientId and clientSecret are copied from the API Access tab on
 // the Google APIs Console
 //   private String clientId     = "1044063429389-dd9oarcgfo2t82qb8tpoiqmrh3h1qpve.apps.googleusercontent.com";
 //   private String clientSecret = "dIURRUZTrU86rvozwKwTXrEd";
    
       private String clientId     = "1044063429389-2gnpsddii8hb6kdhvsmoo4hdi5flmn23.apps.googleusercontent.com";
       private String clientSecret = "0kafoVTz3HMfZCjh3CmiM6Ol";
     
    
 // Or your redirect URL for web based applications.
 // private String redirectUrl  = "urn:ietf:wg:oauth:2.0:oob";   
 // private String redirectUrl  = "http://alainrussier.appspot.com";
    private String redirectUrl = "http://127.0.0.1:8888/gti.html"; 
    
  public String getAuthorizationUrl() throws IllegalArgumentException {  
    String ret = "";
     
    try {
        String scope = "https://www.googleapis.com/auth/tasks.readonly";
               ret   = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope).build();        
    }
    catch(Exception e){       
        e.printStackTrace();
    }     
    return ret;
  }
  
  private Tasks getService (Token token) {      
      Tasks service = null;
      
      try {
          HttpTransport  httpTransport = new NetHttpTransport();
          JacksonFactory jsonFactory   = new JacksonFactory();
          
          System.out.println ("accesToken (p):   " + token.getAccess());
          System.out.println ("refreshToken (p): " + token.getRefresh());
          
          GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(token.getAccess(), httpTransport, jsonFactory, clientId, clientSecret, token.getRefresh());
          
          System.out.println ("accesToken (n)  : " + accessProtectedResource.getAccessToken());
          System.out.println ("refreshToken (n): " + accessProtectedResource.getRefreshToken());

          service = new Tasks(httpTransport, accessProtectedResource, jsonFactory);
          service.setApplicationName("everteam-gtasks-v1");
          
          //accessProtectedResource.refreshToken();
      }
      catch (Exception e) {
          e.printStackTrace();
      }
      
      return service;      
  }

  public Vector<TaskGrid> getList (Token token) {    
      Vector<TaskGrid> vRet = new Vector<TaskGrid> ();
      try {       
          Tasks     taskService = getService (token);          
          TaskLists taskLists   = taskService.tasklists.list().execute();
          for (TaskList taskList : taskLists.items) {             
              vRet.add(new TaskGrid("1", taskList.title, null, null));
              System.out.println("");
              com.google.api.services.tasks.v1.model.Tasks tasks = taskService.tasks.list(taskList.id).execute();
              for (Task task : tasks.items) {
                  vRet.add(new TaskGrid ("2", task.title, task.notes, task.due));                  
                  System.out.print(".");
              }             
          }            
      }
      catch (Exception e) {
          e.printStackTrace();
      }      
      return vRet;
  }

  @Override
  public Token authenticate(String code) {     
      Token token = null;
      try {
          HttpTransport                 httpTransport           = new NetHttpTransport();
          JacksonFactory                jsonFactory             = new JacksonFactory();
          AccessTokenResponse           response                = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory, clientId, clientSecret, code, redirectUrl).execute();
          GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(response.accessToken, httpTransport, jsonFactory, clientId, clientSecret, response.refreshToken);
          
          token = new Token (accessProtectedResource.getAccessToken(), accessProtectedResource.getRefreshToken());
          System.out.println ("code: "         + code);
          System.out.println ("accesToken: "   + token.getAccess());
          System.out.println ("refreshToken: " + token.getRefresh());
          //accessProtectedResource.refreshToken();
      }
      catch (Exception e) {
          e.printStackTrace();
      }
      
      return token;      
  }
}
